<template>
  <page class="home-page">
    <zui-header>
      <logo type="xiaoyanyun" href="/"></logo>
      <h4 class="zui-logo-text">
        |&nbsp;&nbsp;XXXXXXXX
        <br/>|&nbsp;&nbsp;XXXXX
      </h4>
      <div class="zui-rightcol" @click="openMenu" style="color: #0b8ba5;">◄XXXX►</div>
      <drop-list :config="configData" ref="droplist"></drop-list>
      <zui-button @click="onButtonClick('link')">XxXXX</zui-button>
      <zui-button @click="onButtonClick('case')">XXXXXXXX</zui-button>
      <zui-button @click="onButtonClick('plan')">XXXXXXXX</zui-button>
      <zui-button @click="onButtonClick('service')">XXXXXXXX</zui-button>
      <zui-button @click="onButtonClick('home')">XXXX</zui-button>
      <zui-button @click="onButtonClick('AboutMarketing')">关于活动</zui-button>

      <zui-button @click="takePhoto">营销管理系统</zui-button>
      <!--      <zui-button @click="onButtonClick('MarketingManagementSystem')">营销管理系统</zui-button>-->
    </zui-header>


    <div class="banner vivify fadeIn" style="height: 300px">
      <h1 class="vivify popIn">
        <span class="br">XXXXXXXX，</span>XXXXXXXX、XXXXXX、XXXXXX、XXXXXX
      </h1>
      <h3 class="vivify popIn">XXXXXXXXXX，XXXXXXXXXX，XXXXXXXXXX</h3>
    </div>


    <el-row v-if="role !== '管理员'" justify="center" :gutter="20">
      <el-col :span="8" v-for="(item, index) in form" :key="index">
        <el-card class="custom-card" :body-style="{ padding: '8px' }" shadow="hover">
          <div class="card-content">
            <h3 class="title">{{ item.campaignName }}</h3>
            <p class="date">{{ item.des }}</p>
            <p class="date">活动类型：{{ item.campaignType }}</p>
            <p class="date">活动开始日期:{{ item.startDate ? item.startDate.split('T')[0] : '' }}</p>
            <p class="date">活动结束日期:{{ item.endDate ? item.endDate.split('T')[0] : '' }}</p>
            <p class="date">优惠额度：{{ item.budget }}元</p>
            <!-- 其他属性的展示 -->
            <div class="button-container">
              <el-button
                :type="isCampaignJoined(item.campaignID,item.endDate) ? 'default' : 'primary'"
                class="action-button"
                :disabled="isCampaignJoined(item.campaignID,item.endDate)"
                @click="save(item)"
              >
                {{ getButtonText(item.campaignID, item.endDate) }} <!-- 动态绑定按钮文本 -->
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>


    <div>
      <video ref="video" autoplay></video>
      <button @click="takePhoto">拍照</button>
      <canvas ref="canvas" style="display: none;"></canvas>
      <img v-if="photo" :src="photo" alt="拍摄的照片">
    </div>
    <!--    <div>-->
    <!--      <button onclick="startCamera()">开始摄像头</button>-->
    <!--      <video id="videoElement" style="display: none;" autoplay></video>-->
    <!--    </div>-->

  </page>
</template>
<script>
import './less/home-page.less'
import Logo from '../components/Logo'
import Page from '../components/Page'
import ZuiHeader from '../components/Header'
import ZuiFooter from '../components/Footer'
import ZuiButton from '../components/Button'
import feature1 from '../assets/img/feature1.png'
import feature2 from '../assets/img/feature2.png'
import feature3 from '../assets/img/feature3.png'
import feature4 from '../assets/img/feature4.png'
import Util from '../Util'
import DropList from 'vue-droplist'

export default {
  components: {Page, Logo, ZuiHeader, ZuiFooter, ZuiButton, DropList},

  data() {
    return {
      faceCheckResult:null,
      photo: null,
      form: [],
      form_cp_byTID_CID: [],
      saveInfor: {},
      TenantID: 1,
      role: '',
      currentDate: new Date(),
      feature1: feature1,
      feature2: feature2,
      feature3: feature3,
      feature4: feature4,
      carouselPerPage: (Util.os.android || Util.os.iPhone) ? 1 : 2,
      configData: {
        position: {  // XXXXXXXXXXXX，position
          top: '60px',
          right: '15px',
          bottom: '',
          left: ''
        },
        width: '40%', // XXXXXXXX
        list: [ // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
          {text: 'XXXX', action: this.gohome},
          {text: 'XXXXXXXX', action: this.goservice},
          {text: 'XXXXXXXX', action: this.goplan},
          {text: 'XXXXXXXX', action: this.gocase},
          {text: 'XXXXXXXX', action: this.golink},
          {text: 'XXXXXXXX', action: this.goAboutMarketing},
          {text: 'XXXXXXXX', action: this.goMarketingManagementSystem}
        ]
      }
    }
  },
  created() {
    this.load()
  },
  methods: {
    async takePhoto() {
      const video = this.$refs.video;
      const canvas = this.$refs.canvas;

      try {
        // 获取摄像头视频流
        const stream = await navigator.mediaDevices.getUserMedia({video: true});
        video.srcObject = stream;

        // 等待摄像头初始化完成
        await new Promise((resolve) => {
          video.onloadedmetadata = () => {
            video.play();
            // 将视频帧绘制到 canvas 中
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

            // 将 canvas 转换为图片
            this.photo = canvas.toDataURL('image/jpeg');

            // console.log(this.photo)

            // 将图片数据发送给后端
            this.uploadPhoto(this.photo);

            // 停止摄像头视频流
            stream.getTracks().forEach(track => track.stop());

            resolve();
          };
        });
      } catch (error) {
        console.error('摄像头访问出错:', error);
      }


    },
    async uploadPhoto(photoData) {

      try {
        const response = await fetch('http://localhost:8080/AboutMarketing/checkFace', {
          method: 'POST',
          body: JSON.stringify({ photo: photoData }), // 直接发送 Base64 数据
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (response.ok) {
          const responseData = await response.json();
          // 处理后端返回的数据
          if (responseData === true) {
            this.onButtonClick('MarketingManagementSystem')
          } else {
            window.alert("人脸识别失败")
          }
        } else {
          console.error('后端响应错误:', response.statusText);
        }
      } catch (error) {
        console.error('发送请求出错：', error);
      }
    },
    isCampaignJoined(campaignID, endDate) {
      const now = new Date(); // 获取当前时间
      const beijingTime = new Date(now.getTime() + (8 * 60 * 60 * 1000)); // 转换为北京时间
      const yesterdayBeijingTime = new Date(beijingTime.getTime() - (24 * 60 * 60 * 1000)).toISOString();

      if (endDate < yesterdayBeijingTime) return true;

      // return this.form_cp_byTID_CID.includes(campaignID) || endDate < yesterdayBeijingTime;
    },
    getButtonText(campaignID, endDate) {
      const now = new Date(); // 获取当前时间
      const beijingTime = new Date(now.getTime() + (8 * 60 * 60 * 1000)); // 转换为北京时间
      const yesterdayBeijingTime = new Date(beijingTime.getTime() - (24 * 60 * 60 * 1000)).toISOString();
      // console.log(endDate)
      // console.log(now)
      if (endDate < yesterdayBeijingTime) {
        return '已结束'
      }
      if (this.form_cp_byTID_CID.includes(campaignID)) {
        return '已参与'
      }
      return '点击参与';
    },
    save(item) {
      if (this.form_cp_byTID_CID.includes(item.campaignID)) {
        console.log('delete')
        //delete
        const CID = item.campaignID; // 替换为你的CID值
        const TID = this.TenantID; // 替换为你的TID值
        fetch(`http://localhost:8080/AboutMarketing/deletebyCID_TID?CID=${CID}&TID=${TID}`, {
          method: 'DELETE'
        })
          .then(response => {
            if (response.ok) {
              console.log(`删除成功`);
              // 如果需要更新页面或其他操作，可以在这里添加代码
            } else {
              console.error('删除请求未成功');
            }
          })
          .catch(error => {
            console.error('删除请求失败:', error);
          });
        this.load();
      } else {
        this.saveInfor.campaignID = item.campaignID;
        this.saveInfor.tenantID = this.TenantID;
        const currentDate = new Date();
        this.saveInfor.participationDate = currentDate.toISOString();
        console.log(this.saveInfor)
        fetch('http://localhost:8080/AboutMarketing', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.saveInfor)
        })
          .then(res => res.json())
          .then(responseData => {
            // 处理成功响应
            console.log('新增成功:', responseData);
            // 如果需要更新页面或其他操作，可以在这里添加代码
          })
          .catch(error => {
            // 处理错误
            console.error('新增失败:', error);
          });
        this.load();
      }
    },
    load() {
      fetch('http://localhost:8080/MarketingManagementSystem')
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          // 将获取的数据赋值给 form 对象
          this.form = data;
          console.log(this.form); // 输出赋值后的 form 对象，其中包含了获取的 JSON 数据
        })
        .catch(error => {
          console.error('There has been a problem with your fetch operation:', error);
        });


      const queryParams = new URLSearchParams({
        tenantID: this.TenantID,
      });
      fetch(`http://localhost:8080/AboutMarketing/seletebyTenantID?${queryParams}`) // 替换成你的 API 地址
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          // for(let i = 0; i < data.length; i++) {
          //   this.form_cp_byTID_CID[0] = data[i].
          // }
          console.log(data)
          this.form_cp_byTID_CID = data
        })
        .catch(error => {
          console.error('There has been a problem with your fetch operation:', error);
        });


    },
    onButtonClick: function (e) {
      if (e == "home") {
        this.$router.push({path: '/'})
      } else if (e == "service") {
        this.$router.push({path: '/service'})
      } else if (e == "plan") {
        this.$router.push({path: '/plan'})
      } else if (e == "case") {
        this.$router.push({path: '/case'})
      } else if (e == "link") {
        this.$router.push({path: '/link'})
      } else if (e == "AboutMarketing") {
        this.$router.push({path: '/AboutMarketing'})
      } else if (e == "MarketingManagementSystem") {
        this.$router.push({path: '/MarketingManagementSystem'})
      } else {
        this.$router.push({path: '/'})
      }
    },
    openMenu: function () {
      this.$refs.droplist.show()
    },
    gohome: function () {
      this.$router.push({path: '/'})
    },
    goservice: function () {
      this.$router.push({path: '/service'})
    },
    goplan: function () {
      this.$router.push({path: '/plan'})
    },
    gocase: function () {
      this.$router.push({path: '/case'})
    },
    golink: function () {
      this.$router.push({path: '/link'})
    },
    goAboutMarketing: function () {
      this.$router.push({path: '/AboutMarketing'})
    },
    goMarketingManagementSystem: function () {
      this.$router.push({path: '/MarketingManagementSystem'})
    },
  }
}
</script>

<style>
.custom-card {
  padding: 0px;
  margin-left: 40px;
  margin-right: 40px;
  margin-top: 20px;
  margin-bottom: 20px;
  /* 其他样式设置 */
  /* 例如：背景颜色 */
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #ddd;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-content {
  padding: 20px;
}

.title {
  font-size: 1.8em;
  margin-bottom: 10px;
  font-weight: 500;
}

.date {
  font-size: 1.1em;
  color: #888;
  margin-bottom: 10px;
  font-weight: 500;
}

.card-content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%; /* 设置内容容器高度，以便 Flex 生效 */
}

.button-container {
  margin-top: auto; /* 将按钮移动到底部 */
  align-self: flex-end; /* 将按钮对齐到底部右侧 */
}

</style>
